// pages/editGoods/editGoods.js
var g = require('../../utils/goodsCommon.js')
var config = require("../../config.js")
Page({

    /**
     * 页面的初始数据
     */
    data: {
        gid: "",
        goods: {
            N_GB_ID: 0,
            GOODS_ATTR: 1,
            N_ISSETVIPPRICE: 0,
            DISCOUNT_WAY: 2,
            N_INT_NUM: -2,
            // HELP_CODE: "",
            // N_MINPRICE: 0,
            // N_COSTPRICE: 0,
            // VIPPRICE: 0,
            // N_WDJ: 0,
            // N_WDPRICE: 0,
            // UNIT: 0,
            // N_MIN_NUM: -1,
            // N_SORT: "",
            // N_SuperId: "",

        },
        isEdit: false,
        godsClassify: "",
        vipPrice: true,
        score: true,
        showChoose: false,
        classify: [],
        dtpic: [],
        saveText: "新增商品",
        delImg: [],
        chooseImages: false,
        picList: [],
        opInfo: {},
        gglist: [],
        ggname: [],
        getCodeStatus: true,
    },

    setVipPrice(ev) {
        if (ev.detail.value) {
            this.data.goods.N_ISSETVIPPRICE = 1;
        } else {
            this.data.goods.N_ISSETVIPPRICE = 0;
        }
        this.setData({
            goods: this.data.goods
        })
    },

    bindChange(ev) {
        this.data.goods.GOODS_CATEGORY = this.data.classify[ev.detail.value[0]].ID
        this.data.goods.className = this.data.classify[ev.detail.value[0]].CATEGORY_NAME
        this.setData({
            goods: this.data.goods
        })
    },

    chooseClassify() {
        this.setData({
            showChoose: true
        })
    },

    hideDateChoose() {
        this.setData({
            showChoose: false
        })
    },
    // 100010100100
    setScore(ev) {
        if (ev.detail.value) {
            this.data.goods.N_INT_NUM = -1
        } else {
            this.data.goods.N_INT_NUM = -2
        }
        this.setData({
            goods: this.data.goods
        })
    },

    viewPic(ev) {
        var arr = [];
        for (var i = 0; i < this.data.dtpic.length; i++) {
            arr.push(this.data.dtpic[i].PICNAME)
        }
        wx.previewImage({
            current: this.data.dtpic[ev.currentTarget.dataset.i].PICNAME,
            urls: arr,
        })
    },

    /**
     * 创建条码
     */
    createCode() {
        if (this.data.getCodeStatus) {
            g.requestCall({
                bNo: 3205,
                ShopNo: this.data.shopNo,
            }, (data) => {
                if (data) {
                    this.data.goods.C_GBCODE = data;
                    this.setData({
                        getCodeStatus: false,
                        goods: this.data.goods
                    })
                }
            })
        }
    },

    changeLx(ev) {
        this.data.goods.GOODS_ATTR = ev.currentTarget.dataset.i;
        this.setData({
            goods: this.data.goods
        })
    },

    /**
     * 获取商品详情
     */
    getGoodsDetail() {
        g.requestCall({
            bNo: 3201,
            gid: this.data.gid,
            ShopNo: this.data.shopNo
        }, (data) => {
            // 如果当前商品的分类id等于分类列表里的id
            for (var i = 0; i < this.data.classify.length; i++) {
                if (this.data.classify[i].ID == data.Result.GOODS_CATEGORY) {
                    // 设置当前分类的分类名
                    data.Result.className = this.data.classify[i].CATEGORY_NAME
                }
            }

            for (var i = 0; i < data.dtpic.length; i++) {
                data.dtpic[i].PICNAME = config.FilePath + data.dtpic[i].PICNAME;
            }

            // 设置商品数据
            this.setData({
                ggname: data.ggname,
                ggNvlaue: data.ggnamevalue,
                gglist: data.gglist,
                goods: data.Result,
                dtpic: data.dtpic
            })
        })
    },

    /**
     * 获取商品分类
     */
    getGoodsClassify() {
        g.getGoodsClassify({
            bNo: 3100,
            ShopNo: this.data.shopNo
        }, (data) => {
            // 设置结果集
            this.setData({
                classify: data,
            })
            // 获取商品详情
            if (this.data.gid) {
                this.getGoodsDetail();
            } else {
                this.data.goods.GOODS_CATEGORY = data[0].ID;
                this.data.goods.className = data[0].CATEGORY_NAME;
                this.setData({
                    goods: this.data.goods
                })
            }
        })
    },

    /** 
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        if (options.gid) {
            this.data.gid = options.gid;
            this.setData({
                saveText: "保存修改",
                isEdit: true,
            })
        }

        wx.getStorage({
            key: 'OP_INFO',
            success: res => {
                this.data.opInfo = res.data;
            },
        })

        wx.getSystemInfo({
            success: res => {
                this.setData({
                    width: (res.screenWidth - 50) / 4,
                })
            },
        })
    },

    /**
     * 设置商品名称
     */
    setGoodsName(ev) {
        this.data.goods.GOODS_NAME = ev.detail.value;
    },

    /**
     * 设置条码
     */
    setGBcode(ev) {
        this.data.goods.C_GBCODE = ev.detail.value;
    },

    /**
     * 设置商品价格
     */
    setGoodsPrice(ev) {
        this.data.goods.SALE_PRICE = g.filterPrice(ev.detail.value)
        this.setData({
            goods: this.data.goods
        })
    },

    setVippriceData(ev) {
        this.data.goods.VIPPRICE = g.filterPrice(ev.detail.value);
        this.setData({
            goods: this.data.goods
        })
    },

    /**
     * 设置成本价
     */
    setCostpPrice(ev) {
        this.data.goods.N_COSTPRICE = g.filterPrice(ev.detail.value);
        this.setData({
            goods: this.data.goods
        })
    },

    /**
     * 筛选价格
     */
    filterPrice(str) {

    },

    /**
     * 设置单独积分数量
     */
    setGoodsScore(ev) {
        this.data.goods.N_INT_NUM = parseInt(ev.detail.value);
        this.setData({
            goods: this.data.goods
        })
    },

    /**
     * 判断当前商品是否为多规格商品
     * 如果是多规格商品则暂时不允许修改数量和金额
     */
    checkGoodsEdit() {
        if (this.data.gid && this.data.ggname) {
            wx.showModal({
                title: '提示',
                content: '多规格商品暂不支持修改库存与单价',
                showCancel: false,
            })
        }
    },

    /**
     * 设置库存
     */
    setStock(ev) {
        this.data.goods.STOCK = ev.detail.value;
    },

    /**
     * 删除商品图片
     */
    delGoodsPic(ev) {
        // 获取当前操作的图片地址
        var str = this.data.dtpic[ev.currentTarget.dataset.i].PICNAME;
        // 如果当前操作的图片已存在id
        // 表示当前图片为商品已有的图片
        if (this.data.dtpic[ev.currentTarget.dataset.i].ID) {
            // 添加到需要删除的图片队列
            this.data.delImg.push(this.data.dtpic[ev.currentTarget.dataset.i].ID);
        } else {
            // 不然的话就判断为之后上传的图片
            // 在上传的图片列表里筛选该图片，
            for (var i = 0; i < this.data.picList.length; i++) {
                if (str.indexOf(this.data.picList[i].PICNAME)) {
                    // 找到后删掉，编辑的时候不提交
                    this.data.picList.splice(i, 1);
                }
            }
        }

        // 删除商品本身的图片列表的数据
        this.data.dtpic.splice(ev.currentTarget.dataset.i, 1);
        // 重新设置商品数据
        this.setData({
            dtpic: this.data.dtpic
        })
    },

    /**
     * 切换会员折扣方式
     */
    changeShop(ev) {
        this.data.goods.DISCOUNT_WAY = ev.currentTarget.dataset.i;
        this.setData({
            goods: this.data.goods
        })
    },

    /**
     * 切换积分
     */
    changeScore(ev) {
        this.data.goods.N_INT_NUM = ev.currentTarget.dataset.i;
        this.setData({
            goods: this.data.goods
        })
    },

    /**
     * 选择需要上传的商品图片
     */
    chooseGoodsPic() {
        wx.chooseImage({
            count: 1,
            sizeType: ["compressed"],
            success: res => {
                this.data.chooseImages = true;
                // 将用户选择的图片上传
                this.uploadClassifyIcon(res.tempFilePaths[0]);
            },
        })
    },

    /**
     * 上传图片
     */
    uploadClassifyIcon(src) {
        wx.showLoading({
            title: '正在上传',
        })
        wx.uploadFile({
            url: config.requestUrl + "?bNo=1907&isGoods=1",
            filePath: src,
            name: 'file',
            formData: {
                filepath: encodeURI(src)
            },
            success: res => {
                if (res.data) {
                    var data = res.data.replace(/\(|\)/g, "");
                    var data2 = JSON.parse(data);
                    if (data2.code == "100") {
                        // 上传成功
                        // 将新上传的图片添加到商品的图片列表里
                        this.data.dtpic.push({
                            PICNAME: config.FilePath + data2.filepath
                        })

                        // 将新上传的图片添加到需要上传的图片列表里
                        this.data.picList.push({
                            PICNAME: data2.filepath,
                            N_PICLX: 1,
                            N_SPID: 0
                        })

                        // 设置商品图片列表
                        this.setData({
                            dtpic: this.data.dtpic
                        });
                    } else {
                        wx.showToast({
                            title: '图片上传失败，请重试',
                            duration: 1500,
                            icon: "none"
                        })
                    }
                } else {
                    wx.showModal({
                        title: '提示',
                        content: '上传失败',
                        showCancel: false
                    })
                }
            },
            fail: msg => {
                wx.showModal({
                    title: '提示',
                    content: '上传失败',
                    showCancel: false
                })
            },
            complete: () => {
                wx.hideLoading()
            }
        })
    },

    /**
     * 提交商品
     */
    subGoodsInfo() {
        if (!this.data.goods.GOODS_NAME) {
            wx.showModal({
                title: '提示',
                content: '请填写商品名称',
                showCancel: false,
            })
            return;
        }

        if (!this.data.goods.C_GBCODE) {
            wx.showModal({
                title: '提示',
                content: '商品条码不能为空，请填写或者生成',
                showCancel: false,
            })
            return;
        }

        if (!this.data.goods.SALE_PRICE) {
            wx.showModal({
                title: '提示',
                content: '请填写售价',
                showCancel: false,
            })
            return;
        }

        if (!this.data.goods.STOCK) {
            wx.showModal({
                title: '提示',
                content: '请填写库存',
                showCancel: false,
            })
            return;
        }

        if (this.data.goods.DISCOUNT_WAY == 1 && !this.data.goods.VIPPRICE) {
            wx.showModal({
                title: '提示',
                content: '请填写会员统一价',
                showCancel: false,
            })
            return;
        }

        if (this.data.goods.SALE_PRICE < this.data.goods.N_COSTPRICE) {
            wx.showModal({
                title: '提示',
                content: '亲，您输入的商品进价高于销售价了,确认要亏本销售吗？',
                success: ms => {
                    if (ms.confirm) {
                        this.subGoodsInfo();
                    }
                }
            })
        } else {
            this.subGoodsInfo();
        }
    },

    subGoodsInfo() {
        wx.getStorage({
            key: 'C_SHOP_NO',
            success: res => {
                var data = {
                    model: JSON.stringify(this.data.goods),
                    picList: JSON.stringify(this.data.picList),
                    ggName: JSON.stringify(this.data.ggname ? this.data.ggname : []),
                    ggList: JSON.stringify(this.data.gglist),
                    ggNvlaue: JSON.stringify(this.data.ggNvlaue ? this.data.ggNvlaue : []),
                    delImg: this.data.delImg.join(","),
                    opname: this.data.opInfo.c_name,
                    opid: this.data.opInfo.n_ss_id,
                    ShopNo: res.data,
                }
                wx.request({
                    url: config.requestUrl + '?bNo=3203',
                    header: {
                        "content-type": "application/x-www-form-urlencoded"
                    },
                    data,
                    method: "post",
                    success: res => {
                        if (res.data.code === "100" && res.data.Result == 1) {
                            var title = "添加成功";
                            if (this.data.isEdit) {
                                title = "修改成功"
                            }
                            wx.showToast({
                                title,
                                duration: 1000,
                                mask: true,
                                success: res => {
                                    setTimeout(() => {
                                        wx.navigateBack({
                                            delta: 1
                                        })
                                    }, 1000)
                                }
                            })
                        } else {
                            wx.showModal({
                                title: '提示',
                                content: res.data.msg,
                                showCancel: false,
                            })
                        }
                    }
                })
            },
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        
        if (!this.data.chooseImages) {
            console.log("=======")
            wx.getStorage({
                key: "C_SHOP_NO",
                success: res => {
                    this.data.shopNo = res.data;
                    // 获取所有的商品分类
                    this.getGoodsClassify();
                },
            })
        } else {
            console.log("1111111111")
            this.data.chooseImages = false;
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})